package com.glorysoft.wangnianxinpda.activity;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.glorysoft.wangnianxinpda.R;
import com.glorysoft.wangnianxinpda.adapter.AbnoamlCodeDialogAdapter;
import com.glorysoft.wangnianxinpda.adapter.RecipeNameAdapter;
import com.glorysoft.wangnianxinpda.base.App;
import com.glorysoft.wangnianxinpda.base.BaseActivity;
import com.glorysoft.wangnianxinpda.base.Constant;
import com.glorysoft.wangnianxinpda.databinding.ActivityRecipeUpLoadBinding;
import com.glorysoft.wangnianxinpda.entity.AbnomalCodeEntity;
import com.glorysoft.wangnianxinpda.entity.PDARecipeInfoReturnEntity;
import com.glorysoft.wangnianxinpda.entity.net.ResponseEntity;
import com.glorysoft.wangnianxinpda.utils.GsonUtils;
import com.glorysoft.wangnianxinpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class RecipeUpLoadActivity extends BaseActivity {
    private ActivityRecipeUpLoadBinding binding;
    private Context mContext;
    private String sEqpId = "";
    private String sRecipeName = "";

    private PDARecipeInfoReturnEntity mPdaRecipeInfoReturnEntity;
    private List<String> mRecipeInfoList;
    private FreeUI_GeneralFragmentDialog mRecipeNameDialog;//Recipe名称选择框

    @Override
    protected int getLayoutResId() {
        return 0;
    }

    @Override
    protected void initView() {
        mContext = this;
        binding = DataBindingUtil.setContentView(this, R.layout.activity_recipe_up_load);

        binding.flRecipeName.setOnClickListener(v -> showRecipeName());
    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        sEqpId = extras.getString("EQPID");

        mRecipeInfoList = new ArrayList<>();

        RecipeInfo();
        //region 测试
//        String sJson = "{\n" +
//                "          \"HEADER\":           {\n" +
//                "                    \"TRANSACTIONID\": \"8a5694af-bcde-431d-b50b-dd29f5a72bd9\",\n" +
//                "                    \"MESSAGENAME\": \"PDACleanLotResponse\",\n" +
//                "                    \"WORKNO\": \"007\",\n" +
//                "                    \"EVENTUSER\": \"EAP\",\n" +
//                "                    \"EVENTTIME\": \"2021-03-29 14:37:35.208\"\n" +
//                "          },\n" +
//                "          \"BODY\":           {\n" +
//                "                    \"EQPID\": \"DB022\",\n" +
//                "                    \"WORK_NO\": \"\",\n" +
//                "                    \"RECIPE_NAME_LIST\":[      \n" +
//                "                                         {              \n" +
//                "                                           \"RECIPE_NAME\":\"4KUAISU1\"        \n" +
//                "                                         },\n" +
//                "                                         {\n" +
//                "                                           \"RECIPE_NAME\":\"55UAISU1\"\n" +
//                "                                         }\n" +
//                "                    ]\n" +
//                "          },\n" +
//                "          \"RETURN\":           {\n" +
//                "                    \"RETURNCODE\": \"0\",\n" +
//                "                    \"RETURNMESSAGE\": \"获取Recipe列表\"\n" +
//                "          }\n" +
//                "}";
//        try {
//            JSONObject jsonObject = new JSONObject(sJson);
//            String body = jsonObject.getString("BODY");
//            mPdaRecipeInfoReturnEntity = GsonUtils.getObject(body, PDARecipeInfoReturnEntity.class);
//            mRecipeInfoList = mPdaRecipeInfoReturnEntity.getRECIPE_NAME_LIST();
//            binding.setEntity(mPdaRecipeInfoReturnEntity);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        //endregion
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(getString(R.string.recipeUpload));
        freeUI_titleView.setRightListener(getString(R.string.startUpload), v -> upload());
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), binding.llMain);
    }

    //region Recipe名称

    private void showRecipeName(){
        if (mRecipeInfoList != null){
            if (mRecipeInfoList.size() > 0){
                showRecipeNameDialog(mRecipeInfoList);
            }else {
                showToast(getString(R.string.do_no_have_recipe), true);
            }
        }
    }

    //RecipeName选择框
    private void showRecipeNameDialog(List<String> list){
        mRecipeNameDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_recipe_name, null);
        Button btn_cancel = view.findViewById(R.id.btn_cancel);
        RecyclerView rv_reject_code = view.findViewById(R.id.rv_recipe_name);
        btn_cancel.setOnClickListener(v -> mRecipeNameDialog.dismiss());
        mRecipeNameDialog.setLayout(view);
        mRecipeNameDialog.show(getSupportFragmentManager(), "recipeNameSelect");
        mRecipeNameDialog.setCallBack(() -> mRecipeNameDialog = null);//弹出框退出后赋空
        RecipeNameAdapter mAdapter = new RecipeNameAdapter(R.layout.adapter_recipe_name, list);
        rv_reject_code.setLayoutManager(new LinearLayoutManager(mContext));
        rv_reject_code.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener((adapter, view1, position) -> {
            binding.tvRecipeName.setText(list.get(position));
            sRecipeName = binding.tvRecipeName.getText().toString();
            mRecipeNameDialog.dismiss();
        });
    }

    //endregion

    private void upload(){
        if (sRecipeName.equals("")){
            showToast(getString(R.string.please_choose_recipe_name), false);
            return;
        }
        recipeUpload();
    }

    //消息提示框
    private void showMessageDialog(String message, FragmentManager fragmentManager) {
        FreeApi_DialogUtils.getConfirmDialog(
                App.app, "确定", message, this::finish
        ).show(fragmentManager, "DIALOG");

    }

    //region 接口调用
    private void RecipeInfo(){
        FreeUI_EntityCallBack<ResponseEntity<PDARecipeInfoReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<PDARecipeInfoReturnEntity>>(new TypeToken<ResponseEntity<PDARecipeInfoReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<PDARecipeInfoReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(true, getSupportFragmentManager())) {
//                    showToast(response.body().getMsg(), true);

                    mPdaRecipeInfoReturnEntity = response.body().getData();
                    binding.setEntity(mPdaRecipeInfoReturnEntity);
                    if (mRecipeInfoList != null){
                        mRecipeInfoList.clear();
                    }
                    mRecipeInfoList.addAll(mPdaRecipeInfoReturnEntity.getRECIPE_NAME_LIST());

                }
            }

            @Override
            public void onError(Response<ResponseEntity<PDARecipeInfoReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDARecipeInfoRequest");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());
        map.addProperty("EQPID", sEqpId);
        String method = "PDARecipeInfo";
        NetUtils.requestPostNet("PDARecipeInfoRequest", method, this, map, callBack);
    }

    //上传
    private void recipeUpload(){
        FreeUI_EntityCallBack<ResponseEntity<?>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<?>>(new TypeToken<ResponseEntity<?>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<?>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(false, getSupportFragmentManager())) {
                   showMessageDialog(response.body().getMsg(), getSupportFragmentManager());
                }
            }

            @Override
            public void onError(Response<ResponseEntity<?>> response) {
                super.onError(response);
                loadError(response.getException(), "PDALotInfo");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());
        map.addProperty("EQPID", sEqpId);
        map.addProperty("RECIPE_NAME", sRecipeName);
        String method = "PDARecipeUpload";
        NetUtils.requestPostNet("PDARecipeUploadRequest", method, this, map, callBack);
    }

    //endregion
}